﻿package com.wenjh.jdmzt.service.dao;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;

import com.wenjh.jdmzt.util.Log4Android;
import com.wenjh.jdmzt.util.StringUtils;

/**
*
* @author jianhua
*
* @param <T> 对象泛型
* @param <K> 主键泛型
*/
public abstract class BaseDao<T, PK extends Serializable> {
     protected String tableName;
     protected SQLiteDatabase db = null;
     protected Log4Android log = null;
     /*
     * 主键字段名
     */
     private String pk = "_id";

     /**
     * 构造一个数据访问对象，采用此构造器，将默认使用 "_id" 作为主键字段。
     * @param db
     * @param tableName
     */
     public BaseDao(SQLiteDatabase db, String tableName) {
          this.tableName = tableName;
          this.db = db;
          log = new Log4Android(getClass().getSimpleName()).closeDebug();
          log.setMsgPrefix("SQL**==");
     }

     public Log4Android getLogUtil() {
          return log;
     }


     /**
     * 构造一个数据访问对象，并指定主键字段
     * @param db
     * @param tableName
     * @param primaryKey 主键字段
     */
     public BaseDao(SQLiteDatabase db, String tableName, String primaryKey) {
          this(db, tableName);
          this.pk = primaryKey;
     }


     public void closeDebug() {
          log.closeDebug();
     }
    
     public void openDebug() {
          log.openDebug();
     }
    
     public SQLiteDatabase getDb() {
          return db;
     }


     /**
     * 执行一条 sql 语句
     * @param sql sql语句
     * @param parameters 参数
     */
     public void executeSQL(String sql, Object[] parameters) {
          if(db == null) {
               log.i("db instance is null");
               return;
          }
          log.d("executeSQL-->" + sql + "   |-------| params:"+Arrays.toString(parameters));
          checkProcessable();
          
          
          if(parameters != null) {
        	  for (int i = 0; i < parameters.length; i++) {
				Object parameter = parameters[i];
				if(parameter != null && parameter instanceof Date) {
					parameters[i] = toDbTime((Date) parameter);
		        } else if(parameter != null && parameter instanceof Boolean) {
		        	parameters[i] = ((Boolean)parameter) ? 1 : 0;
		        }
			}
          }
          db.execSQL(sql, parameters);
     }

     /**
     * 执行一条无参 sql 语句
     * @param sql
     */
     public void executeSQL(String sql) {
          if(db == null) {
               log.i("db instance is null");
               return;
          }


          log.d("executeSQL-->" + sql);
          checkProcessable();
          db.execSQL(sql);
     }

     /**
     * 查询，返回结果集游标
     * @param sql
     * @param params
     * @return
     */
     public Cursor query(String sql, String[] params) {
          if(db == null) {
               log.i("db instance is null");
               return null;
          }

          log.d("execute query --> " + sql + "  |-------| params:" + Arrays.toString(params));
          return db.rawQuery(sql, params);
     }

     /**
     * 查询，返回组装后的对象
     * @param sql
     * @param params
     * @return
     */
     public T findUnique(String sql, String[] params) {
          if(db == null) {
               log.i("db instance is null");
               return null;
          }

          Cursor cursor = query(sql, params);
          T t = null;
          if(cursor.moveToFirst()) {
               assemble(cursor);
          }
          cursor.close();
          return t;
     }

     /**
     * 执行 SQL 语句，返回对象列表
     * @param sql
     * @param params
     * @return
     */
     public List<T> list(String sql, String[] params) {
          List<T> list = new ArrayList<T>();
          if(db == null) {
               log.i("db instance is null");
               return list;
          }

          Cursor cursor = query(sql, params);
          while(cursor.moveToNext()) {
               list.add(assemble(cursor));
          }
          cursor.close();
          return list;
     }

     /**
     * 根据键、值集合，返回对象列表。并参照某个字段排序。
     * @param fields 字段
     * @param params 参数
     * @param orderField 排序字段
     * @param asc 是否为升序。true表示升序，false为降序
     * @return
     */
     public List<T> list(String[] fields, String[] params, String orderField, boolean asc) {
          List<T> list = new ArrayList<T>();
          if(db == null) {
               log.i("db instance is null");
               return list;
          }

          StringBuilder sql = new StringBuilder("select * from "+ tableName + " ");
          int fieldCount = fields.length;
          if(fieldCount > 0) {
               sql.append("where ");
          }
          for(int i=0; i<fieldCount;) {
               sql.append(fields[i]).append("=? ");
               if(++i < fieldCount) {
                    sql.append("and ");
               }
          }

          sql.append(" order by ").append(orderField);
          if(!asc) {
               sql.append(" desc");
          } else {
               sql.append(" asc");
          }

          Cursor cursor = query(sql.toString(), params);

          while(cursor.moveToNext()) {
               list.add(assemble(cursor));
          }
          cursor.close();
          return list;
     }

     /**
     * 根据键、值集合，返回对象列表。并参照某个字段排序。支持分页操作。
     * @param fields 字段
     * @param params 参数
     * @param orderField 排序字段
     * @param asc 是否为升序。true表示升序，false为降序
     * @param pageStartIndex 分页字段：开始位置
     * @param offset 分页字段：要获取的记录条数
     * @return
     */
     public List<T> list(String[] fields, String[] params, String orderField, boolean asc, int pageStartIndex, int offset) {
          List<T> list = new ArrayList<T>();

          if(db == null) {
               return list;
          }

          StringBuilder sql = new StringBuilder("select * from "+ tableName + " "); // + " limit " + pageStartIndex + "," + offset +


          int fieldCount = fields.length;
          if(fieldCount > 0) {
               sql.append("where ");
          }
          for(int i=0; i<fieldCount;) {
               sql.append(fields[i]).append("=? ");
               if(++i < fieldCount) {
                    sql.append("and ");
               }
          }
         
          if(orderField != null) {
               sql.append(" order by ").append(orderField);
               if(!asc) {
                    sql.append(" asc");
               } else {
                    sql.append(" desc");
               }
          }

          sql.append(" limit ").append(pageStartIndex).append(",").append(offset);

          Cursor cursor = query(sql.toString(), params);

          while(cursor.moveToNext()) {
               list.add(assemble(cursor));
          }
          cursor.close();
          return list;
     }

     /**
     * 根据键、值集合，返回字段列表。并参照某个字段排序。支持分页操作。
     * @param selectField 需要从数据库查询的字段
     * @param fields 字段
     * @param params 参数
     * @param orderField 排序字段
     * @param asc 是否为升序。true表示升序，false为降序
     * @param pageStartIndex 分页字段：开始位置
     * @param offset 分页字段：要获取的记录条数
     * @return
     */
     public List<String> list(String selectField, String[] fields, String[] params, String orderField, boolean asc, int pageStartIndex, int offset) {
          List<String> list = new ArrayList<String>();

          if(db == null) {
               return list;
          }

          StringBuilder sql = new StringBuilder("select "+selectField+" from "+ tableName + " "); // + " limit " + pageStartIndex + "," + offset +


          int fieldCount = fields.length;
          if(fieldCount > 0) {
               sql.append("where ");
          }
          for(int i=0; i<fieldCount;) {
               sql.append(fields[i]).append("=? ");
               if(++i < fieldCount) {
                    sql.append("and ");
               }
          }

          sql.append(" order by ").append(orderField);
          if(!asc) {
               sql.append(" asc");
          } else {
               sql.append(" desc");
          }

          sql.append(" limit ").append(pageStartIndex).append(",").append(offset);

          Cursor cursor = query(sql.toString(), params);

          while(cursor.moveToNext()) {
               list.add(cursor.getString(0));
          }
          cursor.close();
          return list;
     }

     public String[] arrayFiled(String field, String[] fileds, String[] params) {
          StringBuilder sql = new StringBuilder("select "+field+" from " + tableName + " ");

          int fieldCount = fileds.length;
          if(fieldCount > 0) {
               sql.append("where ");
          }
          for(int i=0; i<fieldCount;) {
               sql.append(fileds[i]).append("=? ");
               if(++i < fieldCount) {
                    sql.append("and ");
               }
          }

          List<String> list = new ArrayList<String>();
          Cursor cursor = query(sql.toString(), params);
          while(cursor.moveToNext()) {
               list.add(cursor.getString(0));
          }
          cursor.close();

          String[] arrays = new String[list.size()];

          return list.toArray(arrays);
     }

     /**
     * 根据键、值集合，返回对象列表
     * @param sql
     * @param params
     * @return
     */
     public List<T> list(String[] fields, String[] params) {
          List<T> list = new ArrayList<T>();
          if(db == null) {
               log.i("db instance is null");
               return list;
          }

          StringBuilder sql = new StringBuilder("select * from "+ tableName + " ");
          int fieldCount = fields.length;
          if(fieldCount > 0) {
               sql.append("where ");
          }
          for(int i=0; i<fieldCount;) {
               sql.append(fields[i]).append("=? ");
               if(++i < fieldCount) {
                    sql.append("and ");
               }
          }
          Cursor cursor = query(sql.toString(), params);

          while(cursor.moveToNext()) {
               list.add(assemble(cursor));
          }
          cursor.close();
          return list;
     }

     /**
     * 根据键、值集合，返回对象列表。支持模糊查询
     * @param fields
     * @param params
     * @param fuzzy true表示启用模糊查询, false不启用
     * @param and 筛选条件是 and 还是  or。true表示用and取并集,false反之
     * @return
     */
     public List<T> query(String[] fields, String[] params, boolean fuzzy, boolean and) {
          List<T> list = new ArrayList<T>();
          if(db == null) {
               return list;
          }

          String cs = fuzzy ? " like " : "=";
          String signPre = fuzzy ? "'%" : "";
          String signAfter = fuzzy ? "%'" : "";

          String v = and?" and ":" or ";

          StringBuilder sql = new StringBuilder("select * from "+ tableName + " ");
          int fieldCount = fields.length;
          if(fieldCount > 0) {
               sql.append("where ");
          }
          for(int i=0; i<fieldCount;) {
               sql.append(fields[i]).append(cs + signPre + params[i] + signAfter);
               if(++i < fieldCount) {
                    sql.append(v);
               }
          }

          Cursor cursor = query(sql.toString(), new String[]{});

          while(cursor.moveToNext()) {
               list.add(assemble(cursor));
          }
          cursor.close();
          return list;
     }

     public T max(String filed) {
          return max(filed, new String[]{}, new String[]{});
     }

     public T max(String maxFiled, String[] fields, String[] values) {
          if(db == null) {
               log.i("db instance is null");
               return null;
          }

          StringBuilder sql = new StringBuilder("select * from " + tableName + " where " + maxFiled + "=" + "(select max("+maxFiled+") from "+ tableName +" ");
          int fieldCount = fields.length;
          if(fieldCount > 0) {
               sql.append("where ");
          }
          for(int i=0; i<fieldCount;) {
               sql.append(fields[i]).append("=? ");
               if(++i < fieldCount) {
                    sql.append("and ");
               }
          }

          sql.append(")");

          Cursor cursor = query(sql.toString(), values);
          if(cursor.moveToFirst()) {
               T t = assemble(cursor);
               cursor.close();
               return t;
          }
          return null;
     }

     public String maxField(String selectedField, String maxFiled, String[] fields, String[] values) {
          if(db == null) {
               log.i("db instance is null");
               return null;
          }

          StringBuilder sql = new StringBuilder("select "+selectedField+" from " + tableName + " where " + maxFiled + "=" + "(select max("+maxFiled+") from "+ tableName +" ");
          int fieldCount = fields.length;
          if(fieldCount > 0) {
               sql.append("where ");
          }
          for(int i=0; i<fieldCount;) {
               sql.append(fields[i]).append("=? ");
               if(++i < fieldCount) {
                    sql.append("and ");
               }
          }

          sql.append(")");

          Cursor cursor = query(sql.toString(), values);
          if(cursor.moveToFirst()) {
               String value = cursor.getString(0);
               cursor.close();
               return value;
          }
          return null;
     }

     /**
     * 根据条件，执行查询语句，返回 List 集合<br/>
     * 例如：listBySelection("username=? and password=?", String[] {"wjh", "wjh123"})
     * @param where 条件
     * @param params 参数，如果没有，则传入一个空的数组
     * @return 对象集合
     */
     public List<T> listBySelection(String where, String[] params) {
          String sql = "select * from "+ tableName +" where " + where;
          return list(sql, params);
     }
     
     /**
     * 与params里的值相等的字段的所有记录:select from users where id in (111,222,333);
     * @param field
     * @param params 数组，如：{111,222,333},将自动转换为"111,222,333"样式的字符串
     * @return
     */
     public List<T> listIn(String field, Object[] params, String orderField, boolean asc) {
//          String sql = "select * from "+ tableName +" where " + field + " in ("+StringUtils.join(params, "'", ",")+") ;";
          StringBuffer sql = new StringBuffer();
          sql.append("select * from ").append(tableName).append(" where ").append(field).append(" in (").append(StringUtils.join(params, "'", ",")).append(")");
          if(!StringUtils.isEmpty(orderField)){
               sql.append(" order by ").append(orderField);
               if(!asc) {
                    sql.append(" asc");
               } else {
                    sql.append(" desc");
               }
          }
          return list(sql.toString(), new String[]{});
     }

     /**
     * 验证数据库是否可访问和可写
     */
     protected void checkProcessable() {
          checkAccessable();
          if(db.isReadOnly()) {
               new RuntimeException(new SQLiteException("db is read only"));
          }
     }

     /**
     * 验证数据库是否可访问（未建立连接或连接已关闭）
     */
     protected void checkAccessable() {
          if(db == null) {
               new RuntimeException(new NullPointerException("db is null"));
          }
          if(!db.isOpen()) {
               new RuntimeException(new SQLiteException("db is already closed"));
          }
     }

     /**
     * 获取指定主键值对应的对象
     * @param id
     * @return
     */
     public T get(PK parimaryKey) {
          if(db == null) {
               log.i("db instance is null");
               return null;
          }

          String sql = "select * from "+ tableName +" where "+ this.pk +"=?";
          Cursor cursor = query(sql, new String[]{parimaryKey+""});
          if(cursor.moveToNext()) {
               T t =  assemble(cursor);
               cursor.close();
               return t;
          }
          cursor.close();
          return null;
     }

     public boolean get(T obj, PK parimaryKey) {
          boolean result = false;
         
          if(db == null) {
               log.i("db instance is null");
          }

          String sql = "select * from "+ tableName +" where "+ this.pk +"=?";
          Cursor cursor = query(sql, new String[]{parimaryKey+""});
          if(cursor.moveToNext()) {
               assemble(obj, cursor);
               result = true;
          }
          cursor.close();
          return result;
     }

     public String getFiled(String getFiledName, String[] fields, String[] values) {
          if(db == null) {
               log.i("db instance is null");
               return null;
          }

          StringBuilder sql = new StringBuilder("select "+getFiledName+" from "+ tableName + " ");
          int fieldCount = fields.length;
          if(fieldCount > 0) {
               sql.append("where ");
          }
          for(int i=0; i<fieldCount;) {
               sql.append(fields[i]).append("=? ");
               if(++i < fieldCount) {
                    sql.append("and ");
               }
          }
          Cursor cursor = query(sql.toString(), values);
          String value = null;
          if(cursor.moveToNext()) {
               value =  cursor.getString(0);
          }
          cursor.close();
          return value;
     }

     /**
     * 删除主键值对应的对象
     * @param primary
     */
     public void  delete(PK primaryKey) {
          if(db == null) {
               log.i("db instance is null");
               return;
          }

          String sql = "delete from "+ tableName +" where "+ this.pk +"=?";
          executeSQL(sql, new Object[]{primaryKey});
     }

     /**
     * 删除，按指定字段
     * @param field
     * @param value
     */
     public void delete(String field, Object value) {
          if(db == null) {
               log.i("db instance is null");
               return;
          }

          String sql = "delete from "+ tableName +" where "+ field +"=?";
          executeSQL(sql, new Object[]{value.toString()});
     }

     /**
     * 删除，按指定字段
     * @param field
     * @param value
     */
     public void delete(String[] fields, Object[] values) {
          if(db == null) {
               log.i("db instance is null");
               return;
          }

          StringBuilder sql = new StringBuilder("delete from "+ tableName + " ");
          int fieldCount = fields.length;
          if(fieldCount > 0) {
               sql.append("where ");
          }
          for(int i=0; i<fieldCount;) {
               sql.append(fields[i]).append("=? ");
               if(++i < fieldCount) {
                    sql.append("and ");
               }
          }
          executeSQL(sql.toString(), values);
     }


     /**
     * 获取对象，按指定字段
     * @param field
     * @param value
     */
     public T get(String field, Object value) {
          if(db == null) {
               log.i("db instance is null");
               return null;
          }

          String sql = "select * from "+ tableName +" where "+ field +"=?";
          Cursor cursor = query(sql, new String[]{value.toString()});
          T t = null;
          if(cursor.moveToFirst()) {
               t =  assemble(cursor);
          }
          cursor.close();
          return t;
     }

     /**
     * 获取对象，按指定字段
     * @param fields
     * @param values
     */
     public T get(String[] fields, String[] values) {
          if(db == null) {
               log.i("db instance is null");
               return null;
          }

          StringBuilder sql = new StringBuilder("select * from "+ tableName + " ");
          int fieldCount = fields.length;
          if(fieldCount > 0) {
               sql.append("where ");
          }
          for(int i=0; i<fieldCount;) {
               sql.append(fields[i]).append("=? ");
               if(++i < fieldCount) {
                    sql.append("and ");
               }
          }
          Cursor cursor = query(sql.toString(), values);
          if(cursor.moveToNext()) {
               T t =  assemble(cursor);
               cursor.close();
               return t;
          } else {
        	  cursor.close();
          }
          return null;
     }

     public List<T> getAll() {
          if(db == null) {
               log.i("db instance is null");
               return null;
          }

          List<T> lists = new ArrayList<T>();
          String sql = "select * from " + tableName;
          Cursor cursor = query(sql, new String[]{});
          while(cursor.moveToNext()) {
               lists.add(assemble(cursor));
          }
          cursor.close();
          return lists;
     }


     /**
     * 返回所有，并参照某个字段排序
     * @param orderField 排序字段
     * @param asc 是否为升序。true表示升序，false为降序
     * @return
     */
     public List<T> getAll(String orderField, boolean asc) {
          if(db == null) {
               log.i("db instance is null");
               return null;
          }

          List<T> lists = new ArrayList<T>();
          String sql = "select * from " + tableName + " order by " + orderField;
          if(!asc) {
               sql += " desc";
          }
          Cursor cursor = query(sql, new String[]{});
          while(cursor.moveToNext()) {
               lists.add(assemble(cursor));
          }
          cursor.close();
          return lists;
     }

     /**
     *  按照条件删除对象
     *  例如：listBySelection("username=? and password=?", String[] {"wjh", "wjh123"})
     *
     * @param where 条件
     * @param params 参数，如果没有，则传入一个空的数组
     */
     public void deleteBySelection(String where, Object[] params) {
          if(db == null) {
               log.i("db instance is null");
               return;
          }

          StringBuilder sql = new StringBuilder("delete from "+ tableName + " ");

          sql.append(" where ").append(where);

          executeSQL(sql.toString(), params);
     }

     /**
     * 删除与values串里的值相等的字段的所有记录:delete from users where id in (111,222,333);
     *
     * @param field 字段
     * @param values 数组，如：{111,222,333},将自动转换为"111,222,333"样式的字符串
     */
     public void delelteIn(String field, Object[] values) {
          if(db == null) {
               log.i("db instance is null");
               return;
          }

          StringBuilder sql = new StringBuilder("delete from "+ tableName + " ");
          sql.append(" where ").append(field)
          .append(" in ").append("(").append(StringUtils.join(values, "'", ",")).append(")");
          executeSQL(sql.toString());
     }

     /**
     * 删除所有记录
     */
     public void deleteAll() {
          if(db == null) {
               log.i("db instance is null");
               return;
          }

          executeSQL("delete from " + tableName);
     }

     public void updateField(String field, Object value, PK primaryKey) {
          if(db == null) {
               log.i("db instance is null");
               return;
          }

          updateField(new String[]{field}, new Object[]{value}, new String[]{pk}, new Object[]{primaryKey});
     }


     public void updateField(String[] fields, Object[] values, String[] whereFields, Object[] wherevalues) {
          if(db == null) {
               log.i("db instance is null");
               return;
          }
          
         if(fields.length != values.length) {
     		 throw new SQLiteException("fields.length != values.length");
     	 }
         
         if(whereFields.length != wherevalues.length) {
     		 throw new SQLiteException("whereFields.length != wherevalues.length");
     	 }

          StringBuilder sql = new StringBuilder();
          sql.append("update "+ tableName +" set ");

          Object[] params = new Object[fields.length + whereFields.length];

          for(int i=0; i<fields.length;) {
               params[i] = values[i];

               sql.append(fields[i]).append("=? ");
               if(++i < fields.length) {
                    sql.append(", ");
               }

          }

          int fieldCount = whereFields.length;
          if(fieldCount > 0) {
               sql.append(" where ");
          }
          for(int i=0; i<fieldCount;) {
               params[fields.length + i] = wherevalues[i];

               sql.append(whereFields[i]).append("=? ");
               if(++i < fieldCount) {
                    sql.append("and ");
               }
          }


          executeSQL(sql.toString(), params);
     }
    
     public void insert(String[] fields, Object[] values) {
    	 
    	 if(fields.length != values.length) {
    		 throw new SQLiteException("fields.length != values.length");
    	 }
    	 
          StringBuilder sql = new StringBuilder();
          StringBuilder params = new StringBuilder();

          sql.append("insert into "+ tableName +" (");
         
          for(int i=0; i<fields.length; i++) {
               sql.append(fields[i]);
               params.append("?");
              
               if(i < fields.length-1) {
                    sql.append(", ");
                    params.append(",");
               }
          }
         
          sql.append(") values (");
          sql.append(params);
          sql.append(") ");
         
          executeSQL(sql.toString(), values);
     }

     public void updateIn(String field, Object value, String arrayField, Object[] arrayValues) {
          StringBuilder sql = new StringBuilder();
          sql.append("update "+ tableName +" set ")
             .append(field +"=? ")
            .append(" where "+ arrayField +" in (" + StringUtils.join(arrayValues, "'", ",") +")");

          executeSQL(sql.toString(), new Object[]{value});
     }
    
     T t = null;

     /**
     * 组装数据为对象，子类重写此方法是要注意“不要关闭 Cursor 对象”
     * @param cursor
     * @return
     * @throws Throwable
     */
     protected abstract T assemble(Cursor cursor);
    
     private Field getDeclaredField(Class clazz, String name) {
          Field field= null;
          try {
               field = clazz.getDeclaredField(name);
          } catch (NoSuchFieldException e) {
          }
         
          if(field == null && clazz.getSuperclass() != null) {
               return getDeclaredField(clazz.getSuperclass(), name);
          }
          return field;
     }
    
     protected abstract void assemble(T obj, Cursor cursor);
    
     /**
     * 插入数据
     * @param dayData
     */
     public abstract void insert(T t);

     /**
     * 修改
     * @param dayData
     */
     public abstract void update(T t);

     /**
     * 删除
     * @param obj
     */
     public abstract void deleteInstence(T obj);

     /**
     *  直接删除表
     */
     public void drop() {
          if(db == null) {
               log.i("db instance is null");
               return;
          }

          executeSQL("DROP TABLE IF EXISTS " + tableName);
     }

     /**
     * 验证记录是否存在
     * @return
     */
     public boolean checkExsit(PK primaryKey) {
          return checkExsit(this.pk, primaryKey.toString());
     }

     public boolean checkExsit(String filed, String value) {
          if(db == null) {
               log.i("db instance is null");
               return false;
          }

          return count(new String[]{filed}, new String[]{value}) > 0;
     }

     /**
     * 根据筛选条件，获取记录条数
     *
     * @param fields 筛选字段集合
     * @param params 筛选字段对应的值的集合
     *
     * @return 记录条数。没有对应记录返回为0
     */
     public int count(String[] fields, String[] params) {
          if(db == null) {
               log.i("db instance is null");
               return 0;
          }

          StringBuilder sql = new StringBuilder("select count(*) c from "+ tableName + " ");
          int fieldCount = fields.length;
          if(fieldCount > 0) {
               sql.append("where ");
          }
          for(int i=0; i<fieldCount;) {
               sql.append(fields[i]).append("=? ");
               if(++i < fieldCount) {
                    sql.append("and ");
               }
          }

          Cursor c = query(sql.toString(), params);
          c.moveToFirst();

          int count = c.getInt(0);

          c.close();

          return count;
     }


     public int countIn(String field, String[] params) {
          String sql = "select count(*) c from "+ tableName +" where " + field + " in ("+StringUtils.join(params, "'", ",")+") ;";
          Cursor c = query(sql.toString(), new String[]{});
          c.moveToFirst();

          int count = c.getInt(0);

          c.close();

          return count;
     }

     public int countIn(String field, String[] params, String[] whereFields, String[] whereParams) {
          StringBuilder sql = new StringBuilder("select count(*) c from "+ tableName +" where " + field + " in (" + StringUtils.join(params, "'", ",") + ") ");
          int fieldCount = whereFields.length;
          if(fieldCount > 0) {
               sql.append(" and ");
          }
          for(int i=0; i<fieldCount;) {
               sql.append(whereFields[i]).append("=? ");
               if(++i < fieldCount) {
                    sql.append(" and ");
               }
          }

          Cursor c = query(sql.toString(), whereParams);
          c.moveToFirst();

          int count = c.getInt(0);

          c.close();

          return count;
     }

     /**
     * 日期转换成毫秒数值
     * @param date
     * @return
     */
     public static long toDbTime(Date date) {
          if(date == null) {
               return 0;
          }

          return date.getTime();
     }

     /**
     * 毫秒数值转换成日期
     * @param time
     * @return
     */
     public static Date toDate(long time) {
          if(time <= 0) {
               return null;
          }

          return new Date(time);
     }

}